package com.zcxy.sys.util;

import cn.hutool.core.collection.CollectionUtil;
import com.zcxy.sys.entity.SysDictItem;
import com.zcxy.sys.service.ISysDictService;
import com.zcxy.util.RedisUtils;
import com.zcxy.util.SpringContextHolder;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class SysdictUtil {
    private static final String PRESYSDICT = "sysdict_";

    private static final long ONEDAY = 24 * 60 * 60 * 1000;


    public static Object getSysdictValue(String dictCode, String itemCode) {
        RedisUtils redisUtils = SpringContextHolder.getBean(RedisUtils.class);
        Map map = redisUtils.hmget(SysdictUtil.PRESYSDICT + dictCode);

        if (CollectionUtil.isNotEmpty(map) && map.get(itemCode) != null) {
            return map.get(itemCode);
        } else {
            return SysdictUtil.getSysdictValueByDb(dictCode, itemCode);
        }
    }

    public static Map putSysdictValue(String dictCode, List<SysDictItem> sysDictItems) {
        Map map = new HashMap();
        if (CollectionUtil.isNotEmpty(sysDictItems)) {
            map = sysDictItems.stream().collect(Collectors.toMap(SysDictItem::getCode, SysDictItem::getName));
            RedisUtils redisUtils = SpringContextHolder.getBean(RedisUtils.class);
            redisUtils.hmset(SysdictUtil.PRESYSDICT + dictCode, map, SysdictUtil.ONEDAY);
        }
        return map;
    }


    public static Object getSysdictValueByDb(String dictCode, String itemCode) {
        ISysDictService iSysDictService = SpringContextHolder.getBean(ISysDictService.class);
        List<SysDictItem> items = iSysDictService.queryListSelectDataByCode(dictCode);
        return SysdictUtil.putSysdictValue(dictCode, items).get(itemCode);
    }


}
